package com.cloud.code.真题;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 全排列
 */
public class Demo599 {

    public static void main(String[] args) {
        String[] restaurant = findRestaurant(new String[]{"Shogun","Tapioca Express","Burger King","KFC"}, new String[]{"KFC","Shogun","Burger King"});

        System.out.println(restaurant);
    }

    public static String[] findRestaurant(String[] list1, String[] list2) {
        HashMap<String,Integer> strs =new HashMap<>();
        HashMap<String,Integer> res =new HashMap<>();
        for (int l = 0; l < list1.length; l++) {
            strs.put(list1[l],l);
        }


        for (int i = 0; i < list2.length; i++) {
            Integer integer = strs.get(list2[i]);
            if(integer != null){
                res.put(list2[i],i+integer);
            }
        }

        List<Map.Entry<String,Integer>> list = new ArrayList(res.entrySet());

        list.sort(Comparator.comparingInt(Map.Entry::getValue));
        List<String> ress = new ArrayList<>();
        AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
        res.forEach((s, integer) -> {
            if(min.get() >integer){
                ress.clear();
                ress.add(s);
                min.set(integer);
            }else if(min.get() == integer){
                ress.add(s);
            }
        });


        return ress.toArray(new String[ress.size()]);
    }

}
